package com.zjlanyun.erp.interior.warehouse;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.alibaba.fastjson.JSON;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.utils.DoubleUtils;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;

public class SaleOutBind extends BaseRFIDActivity {

    @Bind(R.id.tv1) TextView tv1;
    @Bind(R.id.tv2) TextView tv2;
    @Bind(R.id.tv3) TextView tv3;
    @Bind(R.id.tv4) TextView tv4;
    @Bind(R.id.tv5) TextView tv5;
    @Bind(R.id.tv6) TextView tv6;
    @Bind(R.id.tv7) TextView tv7;
    @Bind(R.id.tv8) TextView tv8;
    @Bind(R.id.tv9) TextView tv9;
    @Bind(R.id.tv10) TextView tv10;
    @Bind(R.id.lv) ListView lv;
    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_status) TextView tv_status;
    @Bind(R.id.ll_submit) LinearLayout ll_submit;

    private Intent intent;
    private boolean scaning = false;
    private ArrayList<String> epcList;
    private ArrayList<String> epcListDel;
    private JSONObject mData;
    private ArrayList<HashMap<String, Object>> mList;
    private SimpleAdapter simpleAdapter;
    private double count = 0; //平方数合计
    private int juan = 0; //卷数统计
    private boolean noSave = false; //未保存提示
    private int removeIndex = -1;
    private boolean querying = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sale_out_bind);
        initBaseView();
        initView();
        initData();
    }

    private void initView() {
        title.setText("销售出库绑定");
        intent = getIntent();
        ll_submit.setVisibility(View.VISIBLE);

        //提交
        ll_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (count == 0) {
                    Toastor.getInstance().showShortToast("请先扫描出库的产品");
                } else {
                    HashMap<String, Object> param = new HashMap<String, Object>();
                    param.put("list", JSON.toJSONString(epcList));
                    if (epcListDel.size() > 0) {
                        param.put("listDel", JSON.toJSONString(epcListDel));
                    }
                    param.put("FBillNO", mData.optString("FBillNO"));
                    param.put("AutoID", intent.getIntExtra("FEntryID", 0));
                    HttpRequest httpRequest = new HttpRequest(mContext, WebApi.production(), "postSaleOutBind", JSON.toJSONString(param), true, true);
                    httpRequest.send(new SimpleHttpListener<JSONObject>() {
                        @Override
                        public void onSucceed(int what, Response<JSONObject> response) {
                            super.onSucceed(what, response);
                            Toastor.getInstance().showShortToast("提交成功");
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    });
                }
            }
        });

        //返回
        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (noSave) {
                    new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                finish();
                            }
                        }
                    }).show();
                } else {
                    finish();
                }
            }
        });
    }

    private void initData() {
        epcList = new ArrayList<>();
        epcListDel = new ArrayList<>();
        mList = new ArrayList<>();
        simpleAdapter = new SimpleAdapter(mContext, mList, R.layout.sale_out_bind_item, new String[]{"epc", "FBatchNO", "FNumber", "FName", "FModel", "FQty"}, new int[]{R.id.tv_epc, R.id.tv5, R.id.tv1, R.id.tv2, R.id.tv3, R.id.tv4});
        lv.setAdapter(simpleAdapter);
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                removeIndex = position;
                new AlertView("提示", "确定删除吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            juan--;
                            tv9.setText("已扫卷数：" + String.valueOf(juan));
                            double area = (double) mList.get(removeIndex).get("area");
                            count -= area;
                            tv7.setText("已扫数量：" + DoubleUtils.toStringFormat(count, "#.##"));
                            epcListDel.add(epcList.get(removeIndex));
                            mList.remove(removeIndex);
                            epcList.remove(removeIndex);
                            simpleAdapter.notifyDataSetChanged();
                            noSave = true;
                            removeIndex = -1;
                        }
                    }
                }).show();
                return false;
            }
        });
        lv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return false;
            }
        });

        //获取发货单信息
        HashMap<String, Object> param = new HashMap<>();
        param.put("AutoID", intent.getIntExtra("FEntryID", 0));
        HttpRequest httpRequest = new HttpRequest(mContext, WebApi.production(), "getSaleOutBillInfo", JSON.toJSONString(param), true);
        httpRequest.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                mData = response.get().optJSONObject("data");
                tv1.setText("发货单号：" + mData.optString("FBillNO"));
                tv2.setText("产品代码：" + mData.optString("FNumber"));
                tv3.setText("产品名称：" + mData.optString("FName"));
                tv4.setText("数量：" + mData.optDouble("FQty"));
                tv5.setText("单位：" + mData.optString("FUnit"));
                tv6.setText("规格型号：" + mData.optString("FModel"));
                tv8.setText("卷数：" + mData.optString("FJuanShu"));
                tv10.setText("客户：" + mData.optString("FCustName"));

                JSONArray jsonArray = mData.optJSONArray("list");
                for (int i = 0; i < jsonArray.length(); i++) {
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    JSONObject item = jsonArray.optJSONObject(i);
                    double area = DoubleUtils.mul(item.optDouble("FQty"), item.optDouble("FWidth"));
                    map.put("FNumber", "产品代码：" + item.optString("FNumber"));
                    map.put("FName", "产品名称：" + item.optString("FName"));
                    map.put("FModel", "规格型号：" + item.optString("FModel"));
                    map.put("FQty", "数量：" + String.valueOf(area));
                    map.put("epc", "卡号：" + item.optString("FBillNO"));
                    map.put("FBatchNO", "轴号：" + item.optString("FBatchNO"));
                    map.put("area", area);
                    count += area;
                    juan++;
                    epcList.add(item.optString("FBillNO"));
                    mList.add(map);
                }
                tv7.setText("已扫数量：" + DoubleUtils.toStringFormat(count, "#.##"));
                tv9.setText("已扫卷数：" + String.valueOf(juan));
                simpleAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        if (!querying) {
            tv_status.setText("盘询开始");
            scanNumber = 1;
            scaning = true;
            super.startScan();
        }
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            String strEPC = m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", "");
            if (epcList.contains(strEPC)) {
                //设备
                Toastor.getInstance().showShortToast("卡号：" + strEPC + "\n已扫描");
            } else {
                //材料
                getProductInfo(strEPC);
            }
        }
    }

    /**
     * 获取产品信息
     *
     * @param epc
     */
    private void getProductInfo(final String epc) {
        querying = true;
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", epc);
        param.put("FActionFlag", "saleOutBind");
        HttpRequest httpRequest = new HttpRequest(mContext, WebApi.production(), "getProductInfo", JSON.toJSONString(param), true, true);
        httpRequest.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onFinish(int what) {
                super.onFinish(what);
                querying = false;
            }

            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                JSONObject data = response.get().optJSONObject("data");
                if (mData.optString("FNumber").equals(data.optString("FNumber"))) {

                    View view = LayoutInflater.from(mContext).inflate(R.layout.sale_out_bind_item, null);
                    TextView tv1 = (TextView) view.findViewById(R.id.tv1);
                    TextView tv2 = (TextView) view.findViewById(R.id.tv2);
                    TextView tv3 = (TextView) view.findViewById(R.id.tv3);
                    TextView tv4 = (TextView) view.findViewById(R.id.tv4);
                    TextView tv5 = (TextView) view.findViewById(R.id.tv5);
                    TextView tv_epc = (TextView) view.findViewById(R.id.tv_epc);

                    final double area = DoubleUtils.mul(data.optDouble("FQty"), data.optDouble("FCPWidth"));
                    tv1.setText("产品代码：" + data.optString("FNumber"));
                    tv2.setText("产品名称：" + data.optString("FName"));
                    tv3.setText("规格型号：" + data.optString("FModel"));
                    tv4.setText("数量：" + String.valueOf(area));
                    tv5.setText("轴号：" + data.optString("FBatchNO"));
                    tv_epc.setText("卡号：" + data.optString("epc"));

                    final HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("FNumber", "产品代码：" + data.optString("FNumber"));
                    map.put("FName", "产品名称：" + data.optString("FName"));
                    map.put("FModel", "规格型号：" + data.optString("FModel"));
                    map.put("FQty", "数量：" + String.valueOf(area));
                    map.put("epc", "卡号：" + data.optString("epc"));
                    map.put("FBatchNO", "轴号：" + data.optString("FBatchNO"));
                    map.put("area", area);

                    AlertView alertView = new AlertView("提示", null, "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                count += area;
                                tv7.setText("已扫数量：" + DoubleUtils.toStringFormat(count, "#.##"));
                                juan++;
                                tv9.setText("已扫卷数：" + String.valueOf(juan));
                                epcList.add(epc);
                                mList.add(map);
                                simpleAdapter.notifyDataSetChanged();
                                noSave = true;
                            }
                            querying = false;
                        }
                    });
                    alertView.addExtView(view);
                    alertView.show();
                } else {
                    Toastor.getInstance().showShortToast("出库产品不匹配");
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (noSave) {
                new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            finish();
                        }
                    }
                }).show();
                return false;
            }
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
